//
//  CategoryDao.m
//  Contacts
//
//  Created by 武 娇 on 14-8-2.
//  Copyright (c) 2014年 李 雷川. All rights reserved.
//

#import "NoticeCategoryDao.h"

@implementation NoticeCategoryDao

-(BOOL)insertCategory:(NoticeCategory *)category{
    BOOL success = YES;
	[db executeUpdate:[self SQL:@"INSERT INTO %@ (id,name,news_count,sort,ico,image_ico) VALUES(?,?,?,?,?)" inTable:Category_TABLE],
    @(category.ID),
    category.name,
    @(category.newsCount),
    @(category.sort),
    category.ico,
     category.imageIco
     ];
    if ([db hadError]) {
		NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
		success = NO;
    }
	return success;
}
-(BOOL)clearCategory{
    BOOL success = YES;
	[db executeUpdate:[self SQL:@"delete from %@" inTable:Category_TABLE]];
    if ([db hadError]) {
		NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
        success = NO;
	}
    return success;
}
-(BOOL)saveWithCategorys:(NSArray *)categorys{
    BOOL success = YES;
    for (NoticeCategory *category in categorys) {
        [db executeUpdate:[self SQL:@"INSERT INTO %@ (id,name,sort,ico,news_count,image_ico) VALUES(?,?,?,?,?,?)" inTable:Category_TABLE],
         @(category.ID),
         category.name,
         @(category.sort),
          category.ico,
         @(category.newsCount),
         category.imageIco
         ];
        if ([db hadError]) {
            NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
            break;
            success = NO;
        }
    }
	return success;
}
-(NSArray *)getAllCategory{
    FMResultSet *rs =[db executeQuery:[self SQL:@"select * from %@ " inTable:Category_TABLE]];
    NSMutableArray *categorys = nil;
    while ([rs next]) {
        if (!categorys) {
            categorys = [NSMutableArray arrayWithCapacity:10];
        }
       NoticeCategory *category =[self analysisWithRS:rs];
        [categorys addObject:category];
    }
    if ([db hadError]) {
		NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
	}
    return categorys;
}

-(NoticeCategory *)getCategoryWithID:(NSInteger )categoryID{
    NoticeCategory *category = nil;
    
    FMResultSet *rs =[db executeQuery:[self SQL:@"select * from %@ where id = ?" inTable:Category_TABLE],@(categoryID)];
    while ([rs next]) {
        category = [self analysisWithRS:rs];
    }
    if ([db hadError]) {
		NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
	}
    return category;
}

-(NoticeCategory *)analysisWithRS:(FMResultSet *)rs{
    NoticeCategory *category = [[NoticeCategory alloc]init];
    category.ID = [rs intForColumn:@"id"];
    category.name = [rs stringForColumn:@"name"];
    category.newsCount = [rs intForColumn:@"news_count"];
    category.sort =[rs intForColumn:@"sort"];
    category.ico = [rs stringForColumn:@"ico"];
    category.imageIco = [rs stringForColumn:@"image_ico"];
    return category;
}
@end
